import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/cookie'
import Token from '@/api/sys/token'
import User from '@/api/sys/user'

const UserStore = defineStore({
  id: 'user',
  state: () => ({
    token: getToken() || '',
    nickName: '',
    avatar: '',
    roles: [],
    perms: [],
  }),
  actions: {
    async resetState() {
      this.$reset()
    },
    /**
     * 用户登录请求
     * @param loginDTO 登录凭证
     *  username: 用户名
     *  password: 密码
     */
    login(loginDTO) {
      return new Promise((resolve, reject) => {
        Token.login(loginDTO)
          .then(({ result }) => {
            setToken(result)
            this.token = result
            resolve(result)
          })
          .catch((data) => {
            reject(data)
          })
      })
    },
    /**
     *  获取用户信息（昵称、头像、角色集合、权限集合）
     */
    getUserInfo() {
      return new Promise((resolve) => {
        User.userRoleAuth().then(({ result }) => {
          const { username, nickName, avatar, roleList, authList, menuList } = result
          this.username = username
          this.nickName = nickName
          console.log(username, nickName)
          this.avatar = avatar
          this.roles = roleList
          this.perms = authList
          resolve(menuList)
        })
      })
    },

    /**
     *  注销
     */
    logout() {
      return new Promise(async (resolve, reject) => {
        await Token.logout()
        removeToken()
        this.resetState().then()
        resolve(null)
      })
    },

    /**
     * 清除 Token
     */
    async resetToken() {
      removeToken()
      this.resetState().then()
    },

    /**
     * 清除 权限
     */
    async clearPermission() {
      this.perms = []
    },
  },
})

export default UserStore
